package com.yhsimon.realm.member.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhsimon.realm.member.entity.user.LoginRecordEntity;
import com.yhsimon.realm.member.entity.user.UserEntity;
import com.yhsimon.realm.member.service.LoginRecordService;
import com.yhsimon.realm.member.service.UserService;
import com.yhsimon.realm.member.utils.R;
import com.yhsimon.realm.member.vo.user.LoginRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginRecordService loginRecordService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 签到
     */
    @GetMapping("/signIn/{userId}")
    public R signIn(@PathVariable String userId) {
        return userService.signIn(userId);
    }


    /**
     * 累计签到天数
     */
    @GetMapping("/signInCount/{userId}")
    public R signInCount(@PathVariable String userId) {
        Long signInCount = redisTemplate.execute((RedisCallback<Long>) connection -> connection.bitCount(("user:signIn:" + userId).getBytes()));
        return R.ok().put("data", signInCount);
    }

    /**
     * 当月签到情况
     */
    @GetMapping("/getSignInStatus/{userId}")
    public R getSignInStatus(@PathVariable String userId) {
        int[] signInStatus = userService.getSignInStatus(userId);
        return R.ok().put("data", signInStatus);
    }


    /**
     * 用户登录记录信息
     */
    @GetMapping("/getLoginRecordInfo")
    public R getLoginRecordInfo(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size, @RequestParam("userId") String userId) {
        long totalCount = loginRecordService.count(new QueryWrapper<LoginRecordEntity>().eq("user_id", userId));
        List<LoginRecordVo> loginRecordVoList = loginRecordService.getLoginRecordInfo(page, size, Long.parseLong(userId));
        Map<String, Object> map = new HashMap<>();
        map.put("loginRecordList", loginRecordVoList);
        map.put("totalCount", totalCount);
        return R.ok().put("data", map);
    }
}
